<?php 
/**
* 
*/


error_reporting(0);


class GraficoController extends Sgit_Controller_Action
{

    protected $_checkZona = FALSE;
    protected $_checkAcceso = FALSE;
    

    public function _begin()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(TRUE);
    }

    
    private function loadJpgraph($library)
    {
        include_once(APPLICATION_PATH."/library/jpgraph/jpgraph.php");
        include_once(APPLICATION_PATH."/library/jpgraph/jpgraph_$library.php");
        
    }



    public function indexAction()
    {
        $this->_helper->viewRenderer->setNoRender(FALSE);
        $query=$this->getRequest()->getParams();
        
        $query=str_replace('/grafico/index','',$this->getRequest()->getRequestUri());
        
        $this->view->url='/grafico'.$query;
        
        //Zend_Debug::dump($this->view->url);exit();
    }
    

    public function salasAction()
    {
       $graf= new Sgit_Graficos_Salas();
       if($this->_hasParam('json'))
       {
           $this->_helper->viewRenderer->setNoRender(FALSE);
           $graf->googleVisualization($this->view);
           $this->render('json'); 
       }else{
           $graf->jpGrapgh();
       }
    }
    
    public function resumenElectricidadAction()
    {
       $graf= new Sgit_Graficos_ResumenElectricidad();
       if($this->_hasParam('json'))
       {
           $this->_helper->viewRenderer->setNoRender(FALSE);
           $graf->googleVisualization($this->view);
           $this->render('json'); 
       }else{
           $graf->jpGrapgh();
       }
    }
    
    
    public function proveedorAction()
    {
       $graf= new Sgit_Graficos_Proveedores();
       if($this->_hasParam('json'))
       {
           $this->_helper->viewRenderer->setNoRender(FALSE);
           $graf->googleVisualization($this->view);
           $this->render('json'); 
       }else{
           $graf->jpGrapgh();
       }
    }
    
    
    public function proyectosAction()
    {
       $graf= new Sgit_Graficos_ProyectoImputacion();
       if($this->_hasParam('json'))
       {
           $this->_helper->viewRenderer->setNoRender(FALSE);
           $graf->googleVisualization($this->view);
           $this->render('json'); 
       }else{
           $graf->jpGrapgh();
       }
    }
    


    public function lecturasContadorAction()
    {
       
        $this->loadJpgraph('bar');


        $this->_loadModel('Lecturas');
        $this->_loadModel('Contadores');

        $id=    $this->_getParam('id');
        $tipo=  $this->_getParam('tipo','consumo');
        $width= $this->_getParam('w',800);
        $height=$this->_getParam('h',$width * 0.6);
        
        $contador=$this->_model->Contadores->getContador($id);
        $lecturas= $this->_model->Lecturas->getConsumos($id);
        $lecturas=@array_reverse($lecturas,true);
       

        switch($tipo){
            case 'lectura':
                $key='lectura';$tit="Consumo Kwh"; $ytitle='kWh';$format='%d';break;
            case 'consumo':
                $key='consumo';$tit="Consumo Kwh"; $ytitle='kWh';$format='%d';break;
            case 'potencia':
                $key='potencia'; $tit="Potencia Kw";$ytitle='kW';$format='%0.2f';break;
            case 'diff':
                $key='incremento_potencia';$tit="Dif Potencia %"; $ytitle='%';$format='%0.2f';break;
            default:
                 $key='consumo';$tit="Consumo Kwh"; $ytitle='kWh';$format='%d';break;
        }
       



        $title=$tit.' '.$contador['nombre'];
        $subtitle=$contador['proyecto'];
        
        
        $i=0;
        
        
        foreach((array)$lecturas as $j => $v)
        {
            
            $f=new Zend_Date($v['date_consumo'],Zend_Date::ISO_8601);
        	$k=$f->toString('MMM-yy');
            $label[]=$k;
            
            $val[]=($v[$key]) ? $v[$key] : '';
           
        
           
           
            $text1[]=$k;
            $text2[]=$this->view->numEs($v['lectura'],0);
            //if($key=='consumo') $text2.=Utiles::number_formatES($p,0). " kW\n";
        }
    
        $text1=array_reverse($text1);
        $text1=implode(PHP_EOL,$text1);
        $text2=array_reverse($text2);
        $text2=implode(PHP_EOL,$text2);
        

        $step=$this->_step(count($val),$width);
        
        $graph = $this->_graph($width,$height);
        $graph->title->Set(utf8_decode($title));
        $graph->subtitle->Set(utf8_decode($subtitle));
        $graph->SetMargin(75, 150, 30, 80);
        $graph->yaxis->SetTitle($ytitle,'middle'); 
        $graph->xaxis->SetTickLabels($label);
        $graph->xaxis->SetTextLabelInterval($step);


        // Create the bar pot
        $barplot= $this->_barplot($val);
        $barplot->value->Show();
        $barplot->value->SetFont(FF_ARIAL,FS_BOLD,8);
        $barplot->value->SetAngle(90);
        $barplot->value->SetFormat($format);
        $barplot->SetValuePos('center');


        $graph->Add($barplot);
         
         
        
        $txt = new Text($text1);
        $txt->SetPos($width-145, 45);
        $txt->SetFont(FF_ARIAL,FS_ITALIC,7);
        
        $txt2 = new Text($text2);
        $txt2->SetPos($width-90, 45);
        $txt2->SetFont(FF_ARIAL,FS_NORMAL,7);
        
        $txt3 = new Text('Lecturas Kwh');
        $txt3->SetPos($width-145, 30);
        $txt3->SetFont(FF_ARIAL,FS_ITALIC,8);
        
        $graph->AddText($txt); 
        $graph->AddText($txt2); 
        $graph->AddText($txt3);  
         
        $graph->Stroke();
        
    }
    
    
    

    
    public function lecturasContadoresAction()
    {
       
        //include_once(APPLICATION_PATH."/library/jpgraph/jpgraph_bar.php");
        $this->loadJpgraph('bar');
        

        $this->_loadModel('Lecturas');
        $this->_loadModel('Contadores');
        
        

        $ids=    $this->_getParam('id');
        $tipo=  $this->_getParam('tipo','consumo');
        $width= $this->_getParam('w',800);
        $height=$this->_getParam('h',$width * 0.6);
        
       
        $ids=explode(':',$ids);
        
        
                
        //$contador=$this->_model->Contadores->getContador($ids[0]);
        
        foreach($ids as $k => $id)
        {
            $lect= $this->_model->Lecturas->getConsumos($id);
            $lecturas[$k]=@array_reverse($lect,true);
        }
        
        
        

       
        switch($tipo){
            case 'lectura':
                $key='lectura';$tit="Consumo Kwh"; $ytitle='kWh';$format='%d';break;
            case 'consumo':
                $key='consumo';$tit="Consumo Kwh"; $ytitle='kWh';$format='%d';break;
            case 'potencia':
                $key='potencia'; $tit="Potencia Kw";$ytitle='kW';$format='%0.2f';break;
            case 'diff':
                $key='incremento_potencia';$tit="Dif Potencia %"; $ytitle='%';$format='%0.2f';break;
            default:
                 $key='consumo';$tit="Consumo Kwh"; $ytitle='kWh';$format='%d';break;
        }
       




        $title=$tit.' Cuadro';
        $subtitle=$contador['proyecto'];
        
        
        $i=0;
        
        foreach((array)$lecturas as $g => $lectura)
        {
            foreach((array)$lectura as $j => $v)
            {
                $f=new Zend_Date($v['date_consumo'],Zend_Date::ISO_8601);
            	$k=$f->toString('MMM-yy');
                $label[$j]=$k;
                
                $val[$j]+=$lectura[$j][$key];

            }
        }
    
    
        $val=array_values($val);
        $label=array_values($label);


        $step=$this->_step(count($val),$width);
        
        $graph = $this->_graph($width,$height);
        $graph->title->Set(utf8_decode($title));
        $graph->subtitle->Set(utf8_decode($subtitle));
        $graph->SetMargin(75, 75, 30, 80);
        $graph->yaxis->SetTitle($ytitle,'middle'); 
        $graph->xaxis->SetTickLabels($label);
        $graph->xaxis->SetTextLabelInterval($step);


        // Create the bar pot
        $barplot= $this->_barplot($val);
        $barplot->value->Show();
        $barplot->value->SetFont(FF_ARIAL,FS_BOLD,8);
        $barplot->value->SetAngle(90);
        $barplot->value->SetFormat($format);
        $barplot->SetValuePos('center');


        $graph->Add($barplot);
         
         

        $graph->Stroke();
        
    }
    
    
    
    
    
    
    
    function _step($nLabel, $width)
    {
        $step = 1;
        if ($width <= 400) {
            if ($nLabel > 20) $step = 2;
            if ($nLabel > 40) $step = 3;
            if ($nLabel > 60) $step = 4;
            if ($nLabel > 80) $step = 5;
        } else {
            if ($nLabel > 40) $step = 2;
            if ($nLabel > 60) $step = 3;
            if ($nLabel > 80) $step = 4;
        }
        return $step;
    }

    
    
    function _graph($width, $height, $nombre = null, $cache = 14000)
    {
        
        if(is_null($nombre)) {
        	$cache = null;
        }else{
        	if (ETAG == true) $this->_etag($nombre);
        	if (CACHEIMAGENES == false){
        		$nombre=null;$cache=null;
        	} 
        }
        
    
        $graph = new Graph($width, $height, $nombre, $cache);
    
        // Adjust the Graph
        $graph->SetScale('textlin');
        $graph->SetFrame(false);
        $graph->SetMargin(75, 25, 30, 80);
        $graph->SetMarginColor('#FFFFFF');
    
    
        // Adjust the legend
        $graph->legend->SetLayout(LEGEND_HOR);
        $graph->legend->Pos(0, 0.99, "right", "bottom");
        $graph->legend->SetFillColor('#F3F3F3');
        $graph->legend->SetFont(FF_ARIAL, FS_NORMAL, 8);
        $graph->legend->SetShadow(false);
        $graph->legend->SetFrameWeight(0);
        $graph->legend->SetLeftMargin(0);
    
    
        //adjust de Y axis
        $graph->yaxis->title->SetFont(FF_FONT1, FS_BOLD, 9);
        $graph->yaxis->SetTitlemargin(62);
        $graph->yaxis->SetLabelFormatCallback(array($this,'_yLabelFormatSinDec'));
        $graph->yaxis->scale->SetGrace(20);
        $graph->yaxis->SetTitleSide(SIDE_LEFT);
    
    
        //adjust de X axis
        $graph->xaxis->title->SetFont(FF_FONT1, FS_BOLD, 11);
        $graph->xaxis->SetLabelAngle(90);
    
        //adjust the grid
        $graph->ygrid->SetFill(true,'#EFEFEF@0.5','#EFEFEF@0.7');
        $graph->xgrid->Show(false);
    
    
        //adjust the background
       	$graph->SetBackgroundGradient('#FFFFFF@0.5', '#EBCCFF@0.5', GRAD_HOR, BGRAD_PLOT);
    
    
        return $graph;
    }

    
    function _etag($nombre)
    {
        $eTag = substr($nombre, 0, -4);
        header('Etag: ' . $eTag);
        header("Cache-Control: public");
        if (trim($_SERVER['HTTP_IF_NONE_MATCH']) == $eTag)
        {
            header("HTTP/1.1 304 Not Modified");
            exit;
        }
    }

	
    function _linePlot($values, $legend = null, $color = 'red', $width = 1, $mark = true)
    {
        $lineplot = new LinePlot($values);
        $lineplot->SetColor($color);
        $lineplot->SetWeight($width);
        if ($mark) {
            $lineplot->mark->SetType(MARK_FILLEDCIRCLE);
            $lineplot->mark->SetFillColor($color);
            $lineplot->mark->SetWidth($width);
        }
        if (!is_null($legend)) $lineplot->SetLegend($legend);
    
        return $lineplot;
    }
    
    
    function _barPlot($values,$color = 'red', $width = 1.0, $showvalue = true)
    {
        $barplot = new BarPlot($values);
    	$barplot->SetColor($color);
    	$barplot->SetWidth($width);
    	$barplot->SetFillColor("$color@0.5");
    	if($showvalue){
    		$barplot->value->Show();
    		$barplot->value->SetFont(FF_ARIAL,FS_BOLD,7);
    		$barplot->value->SetFormat('%d');
    	}
    
        return $barplot;
    }
    
    
    
    function _yLabelFormatSinDec($aLabel)
    {
        return $this->view->numEs($aLabel, 0);
    }
    function _yLabelFormat($aLabel)
    {
        return $this->view->numEs($aLabel, 2);
    }
    function _yLabelFormat4($aLabel)
    {
        return $this->view->numEs($aLabel, 4);
    }





    function potenciaSistemasAction(){



        $this->loadJpgraph('line');        
        $this->_loadModel('LecturasSistemas');
        $this->_loadModel('ContadoresSistemas');
        
        $id=   $this->_getParam('id');
        $id_sistema=   $this->_getParam('id_sistema');
        $id_zona=   $this->_getParam('idZona');
        $f_lectura=   $this->_getParam('f_lectura',$this->_model->LecturasSistemas->lastFechaLectura(1));

        $limit= $this->_getParam('s',54);
        $json= $this->_getParam('json',0);
        $width= $this->_getParam('w',800);
        $height=$this->_getParam('h',$width * 0.6);        

        if($json) $limit=''; 
        
        
        if($id){
            
            $contador=$this->_model->ContadoresSistemas->getRow($id);
            $title=$contador['nombre'].' '.Sgit_Cache::single()->model('Datacenter')->getKey($contador['id_zona']);;
            $lecturas=$this->_model->LecturasSistemas->lecturasContador($id,$limit);
        }
        
        if($id_sistema)
        {
            if($id_sistema=='6') $title='Ocupación Red Normal '.Sgit_Cache::single()->model('Datacenter')->getKey($id_zona);
            if($id_sistema=='9') $title='Ocupación UPS Clientes '.Sgit_Cache::single()->model('Datacenter')->getKey($id_zona);
            
            $ids=$this->_model->ContadoresSistemas->GetCol('id',array('id_tipo_sistema=?'=>$id_sistema,'id_zona=?'=>$id_zona));
            
            if($id_sistema=='999') {
                $title='Ocupación Total Clientes '.Sgit_Cache::single()->model('Datacenter')->getKey($id_zona);
                $ids=$this->_model->ContadoresSistemas->GetCol('id',array('id_tipo_sistema IN (?)'=>array(9,7,3),'id_zona=?'=>$id_zona));
            
            }
            
            
            $lecturas=$this->_model->LecturasSistemas->lecturasContadores($ids,$limit);
        }
        
        $lecturas=$this->_model->LecturasSistemas->assocArray2($lecturas,'f_lectura');

        $f_semana=Sgit_Filter_DateDbToLocalize::filter($lecturas[$f_lectura]['f_lectura'],'w, EEE dd MMMM yyyy');
        
        $i=0;
        
        foreach($lecturas as $fecha => $v){
        	$label[$i]=date('d/m/y',strtotime($fecha));
            $label2[$i]='Semana '.Sgit_Filter_DateDbToLocalize::filter($fecha,'w, EEE dd MMMM yyyy');
            $date[$i]=$fecha;
        	$val[$i]=($v['potencia']==0) ? '' : (float)$v['potencia'];
            $limite[$i]=$v['potencia_instalada'];
            if($f_lectura==$fecha)
            {
                $hoy=$v;                
                $hoy['i']=$i-1;
                    
            } 

            if($json){
                $datos[]="{c:[
                {v: new Date('{$date[$i]}'), f:'{$label2[$i]}' }, 
                {v: {$val[$i]},f: '".$this->view->numES($val[$i],0)."kW'}, 
                {v: {$limite[$i]},f: '".$this->view->numES($limite[$i],0)."kW'}
                ]}";
            }
            $i++;
        }
        
   
        
        if($json){

            $this->_helper->viewRenderer->setNoRender(FALSE);
            $this->view->title=$title;
            $this->view->options="
                'title': '$title',
                'chartArea': {'height': '80%', 'width': '80%'},
                'hAxis': {'slantedText': false},
                'legend': {'position': 'right'},
                'animation' : {'duration' : 2000},
                'curveType' : 'function',
                'vAxis' : {'title': 'kW'}
            ";
            
            $this->view->data="
            {
             cols: [
                {id: 'task', label: 'Fecha', type: 'date'},
                {id: 'potencia', label: 'Potencia kW', type: 'number'},
                {id: 'limite', label: 'Capacidad kW', type: 'number'}
                ],
            
             rows: [
               ".implode(',',$datos)."
             ]
            }
            ";
           

        }else{

            $step=$this->_step(count($val),$width);
            $yaxistitle='kW';


            $uso=$this->view->numES(100* $hoy['potencia']/$hoy['potencia_instalada'],2);
        
        
            $subtitle="Semana $f_semana | Ocupación ".$this->view->numES($hoy['potencia'],0)." kW | Capacidad: ".$this->view->numES($hoy['potencia_instalada'],0)." kW | Uso: $uso%";
            
            if($id_sistema=='999') {
                $subtitle="Semana $f_semana | Ocupación ".$this->view->numES($hoy['potencia'],0)." kW | Capacidad: ".$this->view->numES($hoy['potencia_instalada'],0)." kW";
            
            }
        

            $graph = $this->_graph($width,$height);
            $graph->title->Set(utf8_decode($title));
            $graph->subtitle->Set(utf8_decode($subtitle));
            $graph->yaxis->SetTitle($yaxistitle,'middle'); 
            $graph->xaxis->SetTickLabels($label);
            $graph->xaxis->SetTextLabelInterval($step);
            
    
            $lineplot1= $this->_linePlot($val,'Ocupación','green',2,false);
            $graph->Add($lineplot1);
            
            if($id_sistema!='999') {
                $lineplot2= $this->_linePlot($limite,'Capacidad','red',1,false);
                $graph->Add($lineplot2);
            }
            
            if(!empty($hoy)){                      
                $linev = new PlotLine(VERTICAL,$hoy['i'],"blue",1);
                $linev->SetLineStyle('dotted'); 
                $graph->AddLine($linev);
            }
            
            $graph->footer->left->Set(utf8_decode("Fuente: Lecturas semanales tomadas por mantenimiento"));
            
            $graph->Stroke();
        }

    }
    
    
    function pueAction(){

        $this->loadJpgraph('line'); 
        $this->_loadModel('LecturasSistemas');
        
        
        $id_zona=   $this->_getParam('idZona');
        $f_lectura= $this->_getParam('f_lectura',$this->_model->LecturasSistemas->lastFechaLectura(1));


        $json= $this->_getParam('json',0);
        $width= $this->_getParam('w',800);
        
      
        $f_inicio= $this->_getParam('f_inicio','2008-01-01');
        if($json) $f_inicio='2008-01-01';
      
      
        $f_fin= $this->_getParam('f_fin',date('Y-m-d'));
        
        $height=$this->_getParam('h',$width * 0.6);          
        if($json) $limit=''; 
        

        
        $pue=new Application_Model_Pue();
        $pue->setFechas($f_inicio,$f_fin);
     


        if(is_numeric($id_zona))
        {
          $pue->setZona(array($id_zona));
            $dat=$pue->getPueSemanal();
            $datos=$dat[$id_zona];
            $zona=Sgit_Cache::single()->model('Datacenter')->getKey($id_zona);
        }else if(!empty($id_zona))
        {
            $z=explode('-',$id_zona);
            $pue->setZona($z);
            foreach($z as $v){
                $g[]=Sgit_Cache::single()->model('Datacenter')->getKey($v);;
            }
            $zona=implode('-',$g);

            $pue->setZona($z);
            $datos=$pue->getPueGlobalSemanal();


        }else{
           $pue->setZona(array(1,2,3,4,6));
            $datos=$pue->getPueGlobalSemanal();
            $zona='Global';
        }



        $title='PUE Semanal '.$zona;
        
        $f_semana=Sgit_Filter_DateDbToLocalize::filter($f_lectura,'w, EEE dd MMMM yyyy');
        
        $subtitle="Semana $f_semana";
      

        $i=0;
        
        foreach($datos as $fecha => $v){
        	$label[$i]=date('d/m/y',strtotime($v['f_lectura']));
            $label2[$i]='Semana '.Sgit_Filter_DateDbToLocalize::filter($v['f_lectura'],'w, EEE dd MMMM yyyy');
            $date[$i]=$v['f_lectura'];
            

            $val1[$i]=($v['pue']==0) ? '' : (float)$v['pue'];
            $v['it']=$this->view->numES($v['it'],0);
            $v['facility']=$this->view->numES($v['facility'],0);
            $data[]="
                {c:[
                    {v: new Date('{$date[$i]}'), f:'{$label2[$i]}' }, 
                    {v: {$val1[$i]},f: 'PUE : {$val1[$i]} Servicio: {$v['facility']}kW IT : {$v['it']}kW'}, 
                ]}";
            if($f_lectura==$v['f_lectura']) {
                $hoy=$v;
                $hoy['fecha']=$i;
            }
            $i++;
        }
        


        
        if($json){

            $this->_helper->viewRenderer->setNoRender(FALSE);
            $this->view->title=$title;
            $this->view->options="
                'title': '$title',
                'chartArea': {'height': '80%', 'width': '80%'},
                'hAxis': {'slantedText': false},
                'legend': {'position': 'right'},
                'animation' : {'duration' : 2000},
                'curveType' : 'function',
                'vAxis' : {'title': 'pue'}
            ";
            
            

            $this->view->data="
                {
                 cols: [
                    {id: 'task', label: 'Fecha', type: 'date'},
                    {id: 'pue1', label: '$zona', type: 'number'},
                    ],
                 rows: [
                   ".implode(',',$data)."
                 ]
                }
                ";
          
  
        }else{
            
            
            
            
            
            $step=$this->_step(count($val1),$width);
            $yaxistitle='kW';

            $graph = $this->_graph($width,$height);

            
            $graph->title->Set(utf8_decode($title));
            $graph->subtitle->Set(utf8_decode($subtitle).' | Servicio: '.$hoy['facility'].'kW | IT: '.$hoy['it'].'kW | PUE: '.$this->view->numES($hoy['pue'],4));
            $graph->yaxis->SetTitle($yaxistitle,'middle'); 
            $graph->xaxis->SetTickLabels($label);
            $graph->xaxis->SetTextLabelInterval($step);
            $graph->xaxis->SetLabelAngle(90);
            $graph->yaxis->SetLabelFormatCallback(array($this,'_yLabelFormat'));
            
            $lineplot1= $this->_linePlot($val1,'PUE Semanal','red',1,false);
            $graph->Add($lineplot1);
 

            if(!empty($hoy)){
                $linev = new PlotLine(VERTICAL,$hoy['fecha'],"blue",1);
                $linev->SetLineStyle('dotted'); 
                $graph->AddLine($linev);
            }
 
 
        
            $graph->footer->left->Set(utf8_decode("Fuente: Lecturas semanales tomadas por mantenimiento"));
            
            $graph->Stroke();
        }

    }
    
    
    function pueAcumuladoAction(){

        $this->loadJpgraph('line'); 
        $this->_loadModel('LecturasSistemas');
        
        
        $id_zona=   $this->_getParam('idZona');
        $f_lectura= $this->_getParam('f_lectura',$this->_model->LecturasSistemas->lastFechaLectura(1));


        $json= $this->_getParam('json',0);
        $width= $this->_getParam('w',800);
        
           
        $height=$this->_getParam('h',$width * 0.7);          
        if($json) $limit=''; 
        
        
        $anio=date('Y',strtotime($f_lectura));
        $date=date('YW',strtotime($f_lectura));
        $anio_ant=$anio-1;
        
        $pue=new Application_Model_Pue();
      
      
      
      
        if(is_numeric($id_zona))
        {
            $pue->setZona(array($id_zona));
            $zona=Sgit_Cache::single()->model('Datacenter')->getKey($id_zona);
            $datos = $pue->getPueSemanalObjetivo($anio);
            $datos=$datos[$id_zona];
        }else if(!empty($id_zona))
        {
            $z=explode('-',$id_zona);
            $pue->setZona($z);
            foreach($z as $v){
                $g[]=Sgit_Cache::single()->model('Datacenter')->getKey($v);
            }
            $zona=implode('-',$g);

            $datos = $pue->getPueGlobalSemanalObjetivo($anio);
        
        }else{
            $pue->setZona(array(1,2,3,4,6));
            $zona='Global';
            $datos = $pue->getPueGlobalSemanalObjetivo($anio);
        }
       


        $objetivos = $pue->getObjetivos();
        $objetivos =$objetivos[$anio];
        
        if(is_numeric($id_zona)){
            $objetivo=$objetivos[$id_zona];
        }else if(!empty($id_zona)){
        
        }else{
            $objetivo=$objetivos['global'];
        }

 

        $title='PUE YTD | Plan vs Actual | '.$zona;
        $f_semana=Sgit_Filter_DateDbToLocalize::filter($f_lectura,'w, EEE dd MMMM yyyy');
        $subtitle="Semana $f_semana";
      
        $i=0;
        foreach($datos as $fecha => $v){
            if(substr($fecha,-2)=='00'){
                $i=0;
                continue;
            }
            
            
        	$label[$i]=$fecha;
            
            
            if(!$json){
                $real[$i]=($v['real']==0) ? '' : (float)$v['real'];
                $anterior[$i]=($v['anterior']==0) ? '' : (float)$v['anterior'];
                $plan[$i]=($v['plan']==0) ? '' : (float)$v['plan'];
                $previsto[$i]=($v['previsto']==0) ? '' : (float)$v['previsto'];
                
                if($date==$fecha) {
                    $hoy=$v;
                    $hoy['w']=date('W',strtotime($f_lectura));
                }
            }
            else
            {
                
                $real2[$i]=!$v['real'] ? 'null' : (float)$v['real'];
                $anterior2[$i]=!$v['anterior'] ? 'null' : (float)$v['anterior'];
                $plan2[$i]=!$v['plan'] ? 'null' : (float)$v['plan'];
                $previsto2[$i]=!$v['previsto'] ? 'null' : (float)$v['previsto'];
                $variacion[$i]=!$v['variacion'] ? 'null' : (float)$v['variacion'];
          
                   $a1=empty($objetivo) ? '': "{v: {$plan2[$i]},f: '".$this->view->numES($plan2[$i],4)."'},";
                
                $f=new Zend_Date();
                $f->setDay(1)->set(substr($fecha,-2),Zend_Date::WEEK);
                $f->set(5,Zend_Date::WEEKDAY_DIGIT);
                $f->set(substr($fecha,0,4),Zend_Date::YEAR);
                
              
                $f=$f->toString('ww , dd MMM yyyy');
            
                $data[]="
                {c:[
                    {v: ".(int)substr($fecha,-2).",f:'Semana $f'}, 
                    {v: {$real2[$i]},f:  '".$this->view->numES($real2[$i],4)."'}, 
                    {v: {$anterior2[$i]},f:  '".$this->view->numES($anterior2[$i],4)."'}, 
                    {v: {$previsto2[$i]},f:  '".$this->view->numES($previsto2[$i],4)."'}, 
                    {v: {$variacion[$i]},f: ''},
                    $a1
                ]}";
            
            }
            
          
            
            $i++;
        }
        


        if($json){
            $this->_helper->viewRenderer->setNoRender(FALSE);
            $this->view->title=$title;
            $this->view->options="
                'title': '$title',
                'chartArea': {'height': '80%', 'width': '80%'},
                'hAxis': {'slantedText': false},
                'legend': {'position': 'right'},
                'animation' : {'duration' : 2000},
                'curveType' : 'function',
                'vAxis' : {'title': 'PUE'},
                series: {
                    0:{color: 'green',lineWidth : 3}, 
                    1:{color: 'red'}, 
                    2:{color: '#00DD00',lineWidth : 1},
                    3:{color: '#00DDDD',lineWidth : 1}
                }
            ";
            
            
            $a2=empty($objetivo) ? '': "{id: 'pue4', label: 'Plan $anio', type: 'number'},";

            $this->view->data="
                {
                 cols: [
                    {id: 'task', label: 'Semana', type: 'number'},
                    {id: 'pue1', label: 'YTD $anio', type: 'number'},
                    {id: 'pue2', label: 'YTD $anio_ant', type: 'number'},
                    {id: 'pue3', label: 'Previsto $anio', type: 'number'},
                    {id: 'pue4', label: 'Variacion Semanal PUE', type: 'number'},
                    $a2
                    ],
                 rows: [
                   ".implode(',',$data)."
                 ]
                }
                ";
          
  
        }else{

            $step=$this->_step(count($anterior),$width);

            $graph = $this->_graph($width,$height);
            $graph->SetMargin(50, 25, 30, 100);
            
            $graph->title->Set(utf8_decode($title));
            $graph->subtitle->Set(utf8_decode($subtitle)." | Actual YTD $anio: ".$this->view->numES($hoy['real'],4).' | Plan YTD: '.$this->view->numES($hoy['plan'],4)." | YTD $anio_ant: ".$this->view->numES($hoy['anterior'],4));
            $graph->xaxis->SetTickLabels($label);
            $graph->xaxis->SetTextLabelInterval($step);
            $graph->xaxis->SetLabelAngle(90);
            
            $graph->yaxis->SetLabelFormatCallback(array($this,'_yLabelFormat'));
            
            $graph->yaxis->SetTitle($yaxistitle,'middle'); 
            $graph->yaxis->scale->SetGrace(0);
            $graph->xaxis->SetTickLabels($label);
            $graph->xaxis->SetTextLabelInterval($step);
            $graph->xaxis->SetLabelAngle(90);
            
            $graph->legend->SetColumns(3);
            $graph->legend->Pos(0, 0.96, "right", "bottom");
            

            $lineplot1= $this->_linePlot($anterior,"PUE YTD $anio_ant",'red',1,false);
            $graph->Add($lineplot1);
            
            $lineplot2= $this->_linePlot($real,"PUE YTD $anio",'green',2,false);
            $graph->Add($lineplot2);

            
            $lineplot4= $this->_linePlot($previsto,"PUE Plan $anio",'green',1,false);
            $lineplot4->SetStyle('dotted');
            $graph->Add($lineplot4);
            
            
            
            if(!empty($objetivo)){
         
                $lineplot3= $this->_linePlot($plan,"PUE Plan $anio",'blue',1,false);
                $lineplot3->SetStyle('dotted');
                $graph->Add($lineplot3);
                
                $line = new PlotLine(HORIZONTAL,$objetivo,"orange",1);
                $line->HideLegend(false);
                $line->SetLegend("Objetivo $anio ".$this->view->numES($objetivo,2));
                $graph->AddLine($line);
            }


            if(!empty($hoy)){
                $linev = new PlotLine(VERTICAL,$hoy['w']-1,"blue",1);
                $linev->SetLineStyle('dotted'); 
                $graph->AddLine($linev);
            }
        
            $graph->footer->left->Set(utf8_decode("Fuente: Lecturas semanales tomadas por mantenimiento"));
            
            $graph->Stroke();
        }

    }
    
    function pueMensualAction(){

        $this->loadJpgraph('line'); 
        $this->_loadModel('LecturasSistemas');
        
        
        $id_zona=   $this->_getParam('idZona');
        $f_lectura= $this->_getParam('f_lectura',$this->_model->LecturasSistemas->lastFechaLectura(1));
        
        $f_lectura=new Zend_Date($f_lectura);
        
        
        
        if($f_lectura->get(Zend_Date::MONTH_SHORT)==date('n'))
        {
        
            if($f_lectura->get(Zend_Date::DAY) > 26)
            {
                $hoymes=$f_lectura->get(Zend_Date::MONTH);
                $f_lectura->set($f_lectura->get(Zend_Date::MONTH_DAYS),Zend_Date::DAY);
            }else{
                $hoymes=$f_lectura->get(Zend_Date::MONTH)-1;
                $f_lectura->set(1,Zend_Date::DAY);
            }
            
        }else
        {
            $hoymes=$f_lectura->get(Zend_Date::MONTH);
            $f_lectura->set($f_lectura->get(Zend_Date::MONTH_DAYS),Zend_Date::DAY);
            
            if(date('d') > date('t')-6)
            {
                $f_lectura=new Zend_Date(date('Y-m-t'));
            }else{
              
                $f_lectura=new Zend_Date(date('Y-m-01'));
                $f_lectura->sub(1,Zend_Date::DAY);
            }
       
        }
       
       
       
        $json= $this->_getParam('json',0);
        $width= $this->_getParam('w',800);
        
           
        $height=$this->_getParam('h',$width * 0.7);          
        if($json) $limit=''; 
        
        $anio=$f_lectura->get(Zend_Date::YEAR);
        $anio_ant=$anio-1;
        

        
        $f_ini=new Zend_Date($f_lectura);
        $f_ini->sub(2,Zend_Date::YEAR)->set(1,Zend_Date::DAY)->set(1,Zend_Date::MONTH);
        $anio_ant2=$f_ini->get(Zend_Date::YEAR);
        
        
        $pue=new Application_Model_Pue();
      
        $pue->setFechas($f_ini->toString('yyyy-MM-dd'),$f_lectura->toString('yyyy-MM-dd'));


        if(is_numeric($id_zona))
        {
           $pue->setZona(array($id_zona));
            $zona=Sgit_Cache::single()->model('Datacenter')->getKey($id_zona);
            $mensual= $pue->getPueMensualZona($id_zona);
            $mensual_actual=$mensual[$anio];
            $mensual_ant=$mensual[$anio_ant];
            $mensual_ant2=$mensual[$anio_ant2];
        }else if(!empty($id_zona))
        {
            $z=explode('-',$id_zona);
            $pue->setZona($z);
            foreach($z as $v){
                $g[]=Sgit_Cache::single()->model('Datacenter')->getKey($v);;
            }
            $zona=implode('-',$g);

            $pue->setZona($z);
            $mensual= $pue->getPueGlobalMensual();
            $mensual_actual=$mensual[$anio];
            $mensual_ant=$mensual[$anio_ant];
            $mensual_ant2=$mensual[$anio_ant2];

        }else{
            $pue->setZona(array(1,2,3,4,6));
            $zona='Global';
            $mensual= $pue->getPueGlobalMensual();
            $mensual_actual=$mensual[$anio];
            $mensual_ant=$mensual[$anio_ant];
            $mensual_ant2=$mensual[$anio_ant2];
        }












        $title="PUE Mensual $zona";
        
      
        $i=0;
        foreach($mensual_ant as $mes => $v){
            
        	$label[$i]=Sgit_Util_Meses::run($mes);
            
            if(!$json)
            {
                $anterior[$i]=!$v['pue'] ? '' : (float)$v['pue'];
                $actual[$i]=!$mensual_actual[$mes]['pue'] ? '' : (float)$mensual_actual[$mes]['pue'];
                $anterior2[$i]=!$mensual_ant2[$mes]['pue'] ? '' : (float)$mensual_ant2[$mes]['pue'];
                
                if($hoymes==$mes) {
                    $hoy=$mensual_actual[$mes];
                    $hoy['w']=$mes;
                }
            }
            else
            {
                $anterior[$i]=!$v['pue'] ? 'null' : (float)$v['pue'];
                $actual[$i]=!$mensual_actual[$mes]['pue'] ? 'null' : (float)$mensual_actual[$mes]['pue'];
                $anterior2[$i]=!$mensual_ant2[$mes]['pue'] ? 'null' : (float)$mensual_ant2[$mes]['pue'];
                $data[]="
                {c:[
                    {v: ".(int)$mes.",f: '".Sgit_Util_Meses::run($mes)."'}, 
                    {v: {$actual[$i]}}, 
                    {v: {$anterior[$i]}}, 
                    {v: {$anterior2[$i]}},
                ]}";
            }
            $i++;
        }



        if($json){
            $this->_helper->viewRenderer->setNoRender(FALSE);
            $this->view->title=$title;
            $this->view->options="
                'title': '$title',
                'chartArea': {'height': '80%', 'width': '80%'},
                'legend': {'position': 'right'},
                'curveType' : 'function',
                'vAxis' : {'title': 'PUE'},
              ";
            $this->view->data="
                {
                 cols: [
                    {id: 'task', label: 'Mes', type: 'number'},
                    {id: 'pue1', label: '$anio', type: 'number'},
                    {id: 'pue2', label: '$anio_ant', type: 'number'},
                    {id: 'pue3', label: '$anio_ant2', type: 'number'},
                    ],
                 rows: [
                   ".implode(',',$data)."
                 ]
                }
                ";
        }else{
            
            $step=$this->_step(count($anterior),$width);

            $graph = $this->_graph($width,$height);
            $graph->SetMargin(50, 25, 30, 100);
            $graph->title->Set(utf8_decode($title));
            $subtitle=Sgit_Util_Meses::run($hoymes). " " .$anio.' | Servicio: '.$this->view->numES($hoy['facility'],0)."kW | IT: ".$this->view->numES($hoy['it'],0)."kW | PUE : ".$this->view->numES($hoy['pue'],4);
            $graph->subtitle->Set(utf8_decode($subtitle));
            $graph->xaxis->SetTickLabels($label);
            $graph->xaxis->SetTextLabelInterval($step);
            $graph->xaxis->SetLabelAngle(90);
            $graph->yaxis->SetLabelFormatCallback(array($this,'_yLabelFormat'));
            $graph->yaxis->SetTitle($yaxistitle,'middle'); 
            $graph->yaxis->scale->SetGrace(0);
            $graph->xaxis->SetTickLabels($label);
            $graph->xaxis->SetTextLabelInterval($step);
            $graph->xaxis->SetLabelAngle(90);
            $graph->legend->SetColumns(3);
            $graph->legend->Pos(0, 0.96, "right", "bottom");
            

            $lineplot2= $this->_linePlot($actual,"$anio",'green',3,false);
            $graph->Add($lineplot2);
            
            $lineplot1= $this->_linePlot($anterior,"$anio_ant",'red',2,false);
            $lineplot1->SetStyle('dotted');
            $graph->Add($lineplot1);
          
            $lineplot3= $this->_linePlot($anterior2,"$anio_ant2",'blue',1,false);
            $lineplot3->SetStyle('dashed');
            $graph->Add($lineplot3);

            if(!empty($hoy)){
                $linev = new PlotLine(VERTICAL,$hoy['w']-1,"blue",1);
                $linev->SetLineStyle('dotted'); 
                $graph->AddLine($linev);
            }
        
            $graph->footer->left->Set(utf8_decode("Fuente: Lecturas semanales tomadas por mantenimiento, media pues semanales de cada mes"));
            $graph->Stroke();
        }

    }
    
    

/*
    function proyecto3Action(){


        $this->loadJpgraph('bar'); 
        $this->loadJpgraph('line'); 
        $this->_loadModel('ImputacionProyectosElectricidad');
        $this->_loadModel('Proyectos');
        
        $key=   $this->_getParam('grafico','potencia');
 
        switch($key){
            case'consumo':
                $y = 'kWh';
                $yaxistitle='kWh';
                $subtitle="Consumo kWh";
                break;
            case'potencia':
                $y = 'W';
                $yaxistitle='Watios';
                $subtitle="Potencia Watios";
                break;
            case'imputacion':
                $y = '€';
                $yaxistitle='Euros';
                $subtitle="Imputación Euros";
                break;
            case'facturacion':
                $y = '€';
                $yaxistitle='Euros';
                $subtitle="Facturación Euros";
                break;
            case'consumo_facturable':
                $y = 'kWh';
                $yaxistitle='kWh';
                $subtitle="Consumo facturable";
                break;
            case'consumo_total':
                $y = 'kWh';
                $yaxistitle='kWh';
                $subtitle="Consumo Total";
                break;
            case'margen':
                $y = '%';
                $yaxistitle='';
                $subtitle="Margen Venta/Coste";
                break;
            case'imputacion_exceso':
                $y = '€';
                $yaxistitle='';
                $subtitle="Imputación Exceso";
                break;
            case'disponibilidad':
                $y = '%';
                $yaxistitle='%';
                $subtitle="% de Utilización";
                break;
            case'ratiowm2':
                  break;
        }
        

        
        $id_proyecto=   $this->_getParam('id_proyecto');
        $json= $this->_getParam('json',0);
        $width= $this->_getParam('w',800);
        
        $start= $this->_getParam('start');
        $end= $this->_getParam('end');
        $height=$this->_getParam('h',$width * 0.5);          

       
        if(empty($start)){
            $f_inicio=new Zend_Date();
            $f_inicio->sub(1,Zend_Date::YEAR)->sub(6,Zend_Date::MONTH)->sub(1,Zend_Date::MONTH);
     
        }else{
            $f_inicio=new Zend_Date($start);
            $f_inicio->sub(1,Zend_Date::MONTH);
        }
       
        if(empty($end)){
            $f_fin=new Zend_Date();
        }else{
            $f_fin=new Zend_Date($end);
        }
        
     



        $filas = $this->_model->ImputacionProyectosElectricidad->getConsumos($id_proyecto);
        $proyecto=$this->_model->Proyectos->GetRow($id_proyecto);
        $filas = array_reverse($filas);
        foreach($filas as $v) {
            $k=$v['anio'].'-'.str_pad($v['mes'],2,'0',STR_PAD_LEFT).'-01';
            $rows[$k]=$v;
        }  
        

        $title=$proyecto['nombre'];

        $i=0;
        
        
        
        foreach($rows as $fecha => $v){
            
            if(!$json){
                $fecha=new Zend_Date($fecha,Zend_Date::ISO_8601);
                if($fecha->isLater($f_inicio) && $fecha->isEarlier($f_fin)){
                    $label[$i]=ucfirst(Sgit_Filter_DateDbToLocalize::filter($fecha,'MMM-yy'));
                    
                    if($key=='potencia') $value['potencia'][$i]=!$v['consumo_equipos_propios'] ? '' :round( 1000*Sgit_Util_Potencia::run($v['consumo_equipos_propios'],$fecha->sub(1,Zend_Date::MONTH)));
                    if($key=='consumo') $value['consumo'][$i]=!$v['consumo_equipos_propios'] ? '' : $v['consumo_equipos_propios'];
                    if($key=='consumo_total') $value['consumo_total'][$i] = !$v['consumo_total'] ? '' : (float)$v['consumo_total'];
                    if($key=='consumo_facturable') $value['consumo_facturable'][$i] = !$v['consumo_facturable'] ? '' : (float)$v['consumo_facturable'];
                    if($key=='imputacion') $value['imputacion'][$i] = !$v['imputacion'] ? '' : (float)$v['imputacion'];
                    if($key=='facturacion') $value['facturacion'][$i] = !$v['facturacion'] ? '' : (float)$v['facturacion'];
                    if($key=='disponibilidad') $value['disponibilidad'][$i] = !$v['disponibilidad'] ? '' : (float)$v['disponibilidad'];
                    if($key=='margen') $value['margen'][$i] =(($v['facturacion'] - $v['imputacion']) / $v['imputacion']) * 100;
                    if($key=='imputacion_exceso') $value['imputacion_exceso'][$i] = !$v['imputacion_exceso'] ? '' : (float)$v['imputacion_exceso'];
                    
    
    
                    if($key == 'ratiowm2'){
                        if($v['id_tip_disp']==2){
                             $yaxistitle = 'Watio/rack';
                             $y='W/rack';
                             $subtitle="Ratio $yaxistitle";
                             $value['ratiowm2'][] = !$v['ratiowm2'] ? '' : (float)$v['ratiowm2']*3;
                        }else{
                            $value['ratiowm2'][] = !$v['ratiowm2'] ? '' : (float)$v['ratiowm2'];
                            $y = 'W/m2';
                            $yaxistitle='Watio/m2';
                            $subtitle="Ratio $yaxistitle";
                        }
                    }
                
                
                
                    $text1[]=$label[$i];
                	$y2=($value[$key][$i]) ? " $y" : "";
                	$text2[]=$this->view->numES($value[$key][$i],0).$y2;
                            
                    $i++;
                }
            } else{
                
                    $fecha=new Zend_Date($fecha,Zend_Date::ISO_8601);
                    $label[$i]=$fecha->toString('yyyy-MM-dd');
                    $label_format[$i]=$fecha->toString('MMM-yyyy');
                    if($key=='potencia') $value['potencia'][$i]=!$v['consumo_equipos_propios'] ? 'null' :round( 1000*Sgit_Util_Potencia::run($v['consumo_equipos_propios'],$fecha->sub(1,Zend_Date::MONTH)));
                    if($key=='consumo') $value['consumo'][$i]=!$v['consumo_equipos_propios'] ? 'null' : $v['consumo_equipos_propios'];
                    if($key=='consumo_total') $value['consumo_total'][$i] = !$v['consumo_total'] ? 'null' : (float)$v['consumo_total'];
                    if($key=='consumo_facturable') $value['consumo_facturable'][$i] = !$v['consumo_facturable'] ? 'null' : (float)$v['consumo_facturable'];
                    if($key=='imputacion') $value['imputacion'][$i] = !$v['imputacion'] ? 'null' : (float)$v['imputacion'];
                    if($key=='facturacion') $value['facturacion'][$i] = !$v['facturacion'] ? 'null' : (float)$v['facturacion'];
                    if($key=='disponibilidad') $value['disponibilidad'][$i] = !$v['disponibilidad'] ? 'null' : (float)$v['disponibilidad'];
                    if($key=='margen') $value['margen'][$i] =(($v['facturacion'] - $v['imputacion']) / $v['imputacion']) * 100;
                    if($key=='imputacion_exceso') $value['imputacion_exceso'][$i] = !$v['imputacion_exceso'] ? 'null' : (float)$v['imputacion_exceso'];
                    
    
    
                    if($key == 'ratiowm2'){
                        if($proyecto['id_tip_disp']==2){
                             $yaxistitle = 'Watio/rack';
                             $y='W/rack';
                             $subtitle="Ratio $yaxistitle";
                             $value['ratiowm2'][] = !$v['ratiowm2'] ? 'null' : (float)$v['ratiowm2']*3;
                        }else{
                            $value['ratiowm2'][] = !$v['ratiowm2'] ? 'null' : (float)$v['ratiowm2'];
                            $y = 'W/m2';
                            $yaxistitle='Watio/m2';
                            $subtitle="Ratio $yaxistitle";
                        }
                    }
                  $i++;
            }
            

        }

     

        
        if($json){

            $this->_helper->viewRenderer->setNoRender(FALSE);
            $this->view->title=$title.' '.$subtitle;
            $this->view->subtitle=$subtitle;
            $this->view->options="
                'title': '{$this->view->title}',
                'hAxis': {'slantedText': true,slantedTextAngle:90},
                'legend': {'position': 'right'},
                'animation' : {'duration' : 2000},
                'curveType' : 'function',
                'vAxis' : {'title': 'pue'},
                 strictFirstColumnType: false,
                'vAxis' : {'minValue': 0, title: '$yaxistitle'},
                 colors:['green'],
      
            ";
            
            $this->view->y=$y;
            $this->view->label=$label;
            $this->view->label_format=$label_format;
            $this->view->data=$value[$key];
 
            
            
            
          
  
        }else{
            
            $text1=array_reverse($text1);
            $text1 = array_slice($text1, 0,floor($width/45));
            $text1=implode(PHP_EOL,$text1);
            
            $text2=array_reverse($text2);
            $text2 = array_slice($text2, 0, floor($width/45));
            $text2=implode(PHP_EOL,$text2);
            
               


            $color='red';
            $step=$this->_step(count($value[$key]),$width);
            

            $graph = $this->_graph($width,$height);
            $graph->SetMargin(75, 150, 30, 80);
            
            $graph->title->Set(utf8_decode($title));
            $graph->subtitle->Set(utf8_decode($subtitle));
            $graph->yaxis->SetTitle($yaxistitle,'middle'); 
            $graph->xaxis->SetTickLabels($label);
            $graph->xaxis->SetTextLabelInterval($step);
            $graph->xaxis->SetLabelAngle(90);

             
            $barplot= $this->_barPlot($value[$key],'red');
            $barplot->value->Show();
            $barplot->value->SetFont(FF_ARIAL,FS_BOLD,8);
            $barplot->value->SetAngle(90);
            $barplot->value->SetFormat('%d');
            $barplot->SetValuePos('center');
            $barplot->SetFillGradient($color.'@0.3',$color.'@0.6',GRAD_VERT);
            $barplot->SetWidth(0.8);
            $graph->Add($barplot);

 
            if($key=='ratiowm2'){
                $sline = new PlotLine(HORIZONTAL, $proyecto['pot_contr'], "red", 2);
                $sline->SetLegend('W/rack Contratado');
                $graph->Add($sline);
            }
      
      
      
            $txt = new Text($text1);
            $txt->SetPos($width-145, 30);
            $txt->SetFont(FF_ARIAL,FS_ITALIC,10);
            $txt2 = new Text($text2);
            $txt2->SetPos($width-90, 30);
            $txt2->SetFont(FF_ARIAL,FS_NORMAL,10);
            
            $graph->AddText($txt); 
            $graph->AddText($txt2); 

      
      

            $graph->Stroke();
        }

    }
    */
    
    function proyectoAction(){


        $this->loadJpgraph('bar'); 
        $this->loadJpgraph('line'); 
        $this->_loadModel('ImputacionProyectosElectricidad');
        $this->_loadModel('Proyectos');
        
        $key=   $this->_getParam('grafico','potencia');
 
        switch($key){
            case'consumo':
                $y = 'kWh';
                $yaxistitle='kWh';
                $subtitle="Consumo kWh";
                break;
            case'potencia':
                $y = 'W';
                $yaxistitle='Watios';
                $subtitle="Potencia Watios";
                break;
            case'imputacion':
                $y = '€';
                $yaxistitle='Euros';
                $subtitle="Imputación Euros";
                break;
            case'facturacion':
                $y = '€';
                $yaxistitle='Euros';
                $subtitle="Facturación Euros";
                break;
            case'consumo_facturable':
                $y = 'kWh';
                $yaxistitle='kWh';
                $subtitle="Consumo facturable";
                break;
            case'consumo_total':
                $y = 'kWh';
                $yaxistitle='kWh';
                $subtitle="Consumo Total";
                break;
            case'margen':
                $y = '%';
                $yaxistitle='';
                $subtitle="Margen Venta/Coste";
                break;
            case'imputacion_exceso':
                $y = '€';
                $yaxistitle='';
                $subtitle="Imputación Exceso";
                break;
            case'disponibilidad_contratada':
                $y = '€';
                $yaxistitle='';
                $subtitle="Imputación Disponibilidad Contratada";
                break;   
            case'disponibilidad_consumida':
                $y = '€';
                $yaxistitle='';
                $subtitle="Imputación Disponibilidad Consumida";
                break;       
            case'disponibilidad':
                $y = '%';
                $yaxistitle='%';
                $subtitle="% de Utilización";
                break;
            case'ratiowm2':
                  break;
        }
        

        
        $id_proyecto=   $this->_getParam('id_proyecto');
        $json= $this->_getParam('json',0);
        $width= $this->_getParam('w',800);
        
        $start= $this->_getParam('start');
        $end= $this->_getParam('end');
        $height=$this->_getParam('h',$width * 0.5);          

       
        if(empty($start)){
            $f_inicio=new Zend_Date();
            $f_inicio->setDay(1)->subYear(1)->subMonth(6)->subMonth(1);
     
        }else{
            $f_inicio=new Zend_Date($start,Zend_Date::ISO_8601);
            $f_inicio->subMonth(1);
        }
       
        if(empty($end)){
            $f_fin=new Zend_Date();
        }else{
            $f_fin=new Zend_Date($end);
        }
        
     
        $proyecto=$this->_model->Proyectos->GetRow($id_proyecto);
        
        
        $values['id_proyecto']=$id_proyecto;
        $values['id_zona']=$proyecto['id_zona'];

        $is_datacenter=Sgit_Validate_isDatacenter::isValid();


        
        $filas = $this->_model->ImputacionProyectosElectricidad->getListadoImputacion($values);
       

        foreach($filas as $v) {
            
            if(!$is_datacenter && !$v['publicado'] ){
               continue;
            }else{
                $k=$v['anio'].'-'.str_pad($v['mes'],2,'0',STR_PAD_LEFT).'-01';
                $rows[$k]=$v;
            }
        }  
        


        $title=$filas[0]['proyecto'];

        $i=0;
        foreach($rows as $fecha => $v)
        {
            
            
            if(!$json){
                $fecha=new Zend_Date($fecha,Zend_Date::ISO_8601);
                if($fecha->isLater($f_inicio) && $fecha->isEarlier($f_fin)){
                    $label[$i]=ucfirst(Sgit_Filter_DateDbToLocalize::filter($fecha,'MMM-yy'));
                    
                    if($key=='potencia') $value['potencia'][$i]=!$v['consumo_equipos_propios'] ? '' :round( 1000*Sgit_Util_Potencia::run($v['consumo_equipos_propios'],$fecha->sub(1,Zend_Date::MONTH)));
                    if($key=='consumo') $value['consumo'][$i]=!$v['consumo_equipos_propios'] ? '' : $v['consumo_equipos_propios'];
                    if($key=='consumo_total') $value['consumo_total'][$i] = !$v['consumo_total'] ? '' : (float)$v['consumo_total'];
                    if($key=='consumo_facturable') $value['consumo_facturable'][$i] = !$v['consumo_facturable'] ? '' : (float)$v['consumo_facturable'];
                    if($key=='imputacion') $value['imputacion'][$i] = !$v['imputacion'] ? '' : (float)$v['imputacion'];
                    if($key=='facturacion') $value['facturacion'][$i] = !$v['facturacion'] ? '' : (float)$v['facturacion'];
                    if($key=='disponibilidad') $value['disponibilidad'][$i] = !$v['disponibilidad'] ? '' : (float)$v['disponibilidad'];
                    if($key=='imputacion_exceso') $value['imputacion_exceso'][$i] = !$v['imputacion_exceso'] ? '' : (float)$v['imputacion_exceso'];
                    
                    if($key=='disponibilidad_contratada') $value['disponibilidad_contratada'][$i] = !$v['disponibilidad_precio'] ? '' : (float)$v['disponibilidad_precio'];
                    if($key=='disponibilidad_consumida') $value['disponibilidad_consumida'][$i] = !$v['disponibilidad_precio_exceso'] ? '' : (float)$v['disponibilidad_precio_exceso'];
                   
                    
                    // if($key=='margen') $value['margen'][$i] =(($v['facturacion'] - $v['imputacion']) / $v['imputacion']) * 100;
                    if($key=='margen') $value['margen'][$i] = !$v['margen'] ? '' : (float)$v['margen'];
                    
    
                    if($key == 'ratiowm2'){
                        if($v['id_tip_disp']==2){
                             $yaxistitle = 'Watio/rack';
                             $y='W/rack';
                             $subtitle="Ratio $yaxistitle";
                             $value['ratiowm2'][] = !$v['ratiowm2'] ? '' : (float)$v['ratiowm2']*3;
                        }else{
                            $value['ratiowm2'][] = !$v['ratiowm2'] ? '' : (float)$v['ratiowm2'];
                            $y = 'W/m2';
                            $yaxistitle='Watio/m2';
                            $subtitle="Ratio $yaxistitle";
                        }
                    }
                
  
                    $text1[]=$label[$i];
                	$y2=($value[$key][$i]) ? " $y" : "";
                	$text2[]=$this->view->numES($value[$key][$i],0).$y2;
                            
                    $i++;
                }
            } else{
                
                    $fecha=new Zend_Date($fecha,Zend_Date::ISO_8601);
                    $label[$i]=$fecha->toString('yyyy-MM-dd');
                    $label_format[$i]=$fecha->toString('MMM-yyyy');
                    if($key=='potencia') $value['potencia'][$i]=!$v['consumo_equipos_propios'] ? 'null' :round( 1000*Sgit_Util_Potencia::run($v['consumo_equipos_propios'],$fecha->sub(1,Zend_Date::MONTH)));
                    if($key=='consumo') $value['consumo'][$i]=!$v['consumo_equipos_propios'] ? 'null' : $v['consumo_equipos_propios'];
                    if($key=='consumo_total') $value['consumo_total'][$i] = !$v['consumo_total'] ? 'null' : (float)$v['consumo_total'];
                    if($key=='consumo_facturable') $value['consumo_facturable'][$i] = !$v['consumo_facturable'] ? 'null' : (float)$v['consumo_facturable'];
                    if($key=='imputacion') $value['imputacion'][$i] = !$v['imputacion'] ? 'null' : (float)$v['imputacion'];
                    if($key=='facturacion') $value['facturacion'][$i] = !$v['facturacion'] ? 'null' : (float)$v['facturacion'];
                    if($key=='disponibilidad') $value['disponibilidad'][$i] = !$v['disponibilidad'] ? 'null' : (float)$v['disponibilidad'];
                    
                    if($key=='imputacion_exceso') $value['imputacion_exceso'][$i] = !$v['imputacion_exceso'] ? 'null' : (float)$v['imputacion_exceso'];
                    if($key=='disponibilidad_contratada') $value['disponibilidad_contratada'][$i] = !$v['disponibilidad_precio'] ? 'null' : (float)$v['disponibilidad_precio'];
                    if($key=='disponibilidad_consumida') $value['disponibilidad_consumida'][$i] = !$v['disponibilidad_precio_exceso'] ? 'null' : (float)$v['disponibilidad_precio_exceso'];
                   
                   
                   
                    //if($key=='margen') $value['margen'][$i] =(($v['facturacion'] - $v['imputacion']) / $v['imputacion']) * 100;
                    if($key=='margen') $value['margen'][$i] = !$v['margen'] ? 'null' : (float)$v['margen'];
                    
    
    
                    if($key == 'ratiowm2'){
                        if($v['id_tip_disp']==2){
                             $yaxistitle = 'Watio/rack';
                             $y='W/rack';
                             $subtitle="Ratio $yaxistitle";
                             $value['ratiowm2'][] = !$v['ratiowm2'] ? 'null' : (float)$v['ratiowm2']*3;
                        }else{
                            $value['ratiowm2'][] = !$v['ratiowm2'] ? 'null' : (float)$v['ratiowm2'];
                            $y = 'W/m2';
                            $yaxistitle='Watio/m2';
                            $subtitle="Ratio $yaxistitle";
                        }
                    }
                  $i++;
            }
            

        }

     

        
        if($json){

            $this->_helper->viewRenderer->setNoRender(FALSE);
            $this->view->title=$title.' '.$subtitle;
            $this->view->subtitle=$subtitle;
            $this->view->options="
                'title': '{$this->view->title}',
                'hAxis': {'slantedText': true,slantedTextAngle:90},
                'legend': {'position': 'right'},
                'animation' : {'duration' : 2000},
                'curveType' : 'function',
                'vAxis' : {'title': 'pue'},
                 strictFirstColumnType: false,
                'vAxis' : {'minValue': 0, title: '$yaxistitle'},
                 colors:['green'],
      
            ";
            
            $this->view->y=$y;
            $this->view->label=$label;
            $this->view->label_format=$label_format;
            $this->view->data=$value[$key];
 
            
            $this->render('json');
            
          
  
        }else{
            
            $text1=array_reverse($text1);
            $text1 = array_slice($text1, 0,floor($width/45));
            $text1=implode(PHP_EOL,$text1);
            
            $text2=array_reverse($text2);
            $text2 = array_slice($text2, 0, floor($width/45));
            $text2=implode(PHP_EOL,$text2);
            


            $color='red';
            $step=$this->_step(count($value[$key]),$width);
            

            $graph = $this->_graph($width,$height);
            $graph->SetMargin(75, 150, 30, 80);
            
            $graph->title->Set(utf8_decode($title));
            $graph->subtitle->Set(utf8_decode($subtitle));
            $graph->yaxis->SetTitle($yaxistitle,'middle'); 
            $graph->xaxis->SetTickLabels($label);
            $graph->xaxis->SetTextLabelInterval($step);
            $graph->xaxis->SetLabelAngle(90);

             
            $barplot= $this->_barPlot($value[$key],'red');
            $barplot->value->Show();
            $barplot->value->SetFont(FF_ARIAL,FS_BOLD,8);
            $barplot->value->SetAngle(90);
            $barplot->value->SetFormat('%d');
            $barplot->SetValuePos('center');
            $barplot->SetFillGradient($color.'@0.3',$color.'@0.6',GRAD_VERT);
            $barplot->SetWidth(0.8);
            $graph->Add($barplot);

 
            if($key=='ratiowm2'){
                $sline = new PlotLine(HORIZONTAL, $proyecto['pot_contr'], "red", 2);
                $sline->SetLegend('W/rack Contratado');
                $graph->Add($sline);
                /*
                $sline = new PlotLine(HORIZONTAL, 1000, "green", 2);
                $sline->SetLegend('W/rack revisado');
                $graph->Add($sline);*/
                
            }
      
      
      
            $txt = new Text($text1);
            $txt->SetPos($width-145, 30);
            $txt->SetFont(FF_ARIAL,FS_ITALIC,10);
            $txt2 = new Text($text2);
            $txt2->SetPos($width-90, 30);
            $txt2->SetFont(FF_ARIAL,FS_NORMAL,10);
            
            $graph->AddText($txt); 
            $graph->AddText($txt2); 

      
            $graph->footer->left->Set(utf8_decode("Fuente: Lecturas mensuales de contadores del cliente"));
            $graph->Stroke();
        }

    }
    
    
    /*
    function salaAction(){


        $this->loadJpgraph('bar'); 
        $this->loadJpgraph('line'); 
        $this->_loadModel('InformeElectricidadMensualSalas');

        $key=   $this->_getParam('grafico','precio');
 
        $id_sala=   $this->_getParam('id_sala');
        $id_zona=   $this->_getParam('idZona');
 
 
        switch($key){
            case'consumo':
                $y = 'kWh';
                $yaxistitle='kWh';
                $subtitle="Consumo kWh";
                $format='%d';
                break;
            case'potencia':
                $y = 'kW';
                $yaxistitle='kW';
                $subtitle="Potencia kW";
                $format='%d';
                break;

            case'ratiowm2':
                $y = 'W/m2';
                $yaxistitle='W/m2';
                $subtitle="Ratio W/m2";
                $format='%d';
                break;
          
        }
        

        $json= $this->_getParam('json',0);
        $width= $this->_getParam('w',800);
        
        $limit= $this->_getParam('limit',28);
        $height=$this->_getParam('h',$width * 0.5);          

       

         
        $filas = $this->_model->InformeElectricidadMensualSalas->getAll(array('id_sala=?'=>$id_sala),array('anio DESC','mes desc'),null,$limit);
        $filas=array_reverse($filas);
        
        $m_sala=new Application_Model_Salas();
        $sala=$m_sala->getRow($id_sala);
        
        
        $title='Sala: '.$sala['nombre'].' '.Sgit_Cache::single()->model('Datacenter')->getKey($filas[0]['id_zona']);
      $subtitle=$subtitle.' Superfice Neta:'. $this->view->numES($sala['sup_neta'],2).' m2';


        $i=0;
        $fecha=new Zend_Date();
        
        foreach($filas as $v)
        {

            $fecha->setMonth($v['mes'])->setYear($v['anio']);
            

            $v['potencia']=Sgit_Util_Potencia::run($v['consumo'],$fecha);
            $v['ratiowm2']=$v['potencia']*1000/$sala['sup_neta'];
          
            if(!$json)
            {
                    $label[$i]=ucfirst($fecha->get('MMM-yy'));
                    $value['potencia'][$i]=!$v['potencia'] ? '' : (float)$v['potencia'];
                    $value['consumo'][$i] =!$v['consumo']  ? '' : (float)$v['consumo'];
                    $value['ratiowm2'][$i] =!$v['ratiowm2']  ? '' : (float)$v['ratiowm2'];
                    $value['ratiowm2_neto'][$i] =!$v['ratiowm2_neto']  ? '' : (float)$v['ratiowm2_neto'];
            

                    $text1[]=$label[$i];
                	$y2=($value[$key][$i]) ? " $y" : "";
               		$text2[]=$this->view->numES($value[$key][$i],0).$y2;

                    $i++;
            } else{
                
                    $label[$i]=$fecha->toString('yyyy-MM-dd');
                    $label_format[$i]=$fecha->toString('MMM-yyyy');

                    $value['potencia'][$i]=!$v['potencia'] ? 'null' : (float)$v['potencia'];
                    $value['consumo'][$i] =!$v['consumo']  ? 'null' : (float)$v['consumo'];
                    $value['ratiowm2'][$i] =!$v['ratiowm2']  ? 'null' : (float)$v['ratiowm2'];
                    $value['ratiowm2_neto'][$i] =!$v['ratiowm2_neto']  ? 'null' : (float)$v['ratiowm2_neto'];
            
                   $i++;
            }
        }



        if($json){

            $this->_helper->viewRenderer->setNoRender(FALSE);
            $this->view->title=$title.' '.$subtitle;
            $this->view->subtitle=$subtitle;
            $this->view->options="
                'title': '{$this->view->title}',
                'hAxis': {'slantedText': true,slantedTextAngle:90},
                'legend': {'position': 'right'},
                'animation' : {'duration' : 2000},
                'curveType' : 'function',
                'vAxis' : {'title': 'pue'},
                 strictFirstColumnType: false,
                'vAxis' : {'minValue': 0, title: '$yaxistitle'},
                 colors:['green'],
      
            ";
            
            $this->view->y=$y;
            $this->view->label=$label;
            $this->view->label_format=$label_format;
            $this->view->data=$value[$key];
 
            $this->render('json');

  
        }else{
            
            $text1=array_reverse($text1);
            $text1 = array_slice($text1, 0,floor($width/40));
            $text1=implode(PHP_EOL,$text1);
            
            $text2=array_reverse($text2);
            $text2 = array_slice($text2, 0, floor($width/40));
            $text2=implode(PHP_EOL,$text2);
            
            $color='red';
            $step=$this->_step(count($value[$key]),$width);
            

           // $nombre=md5($key.$width.$height.serialize($filas));

 
            
            $graph = $this->_graph($width,$height,$nombre);
            $graph->SetMargin(75, 150, 30, 80);

            $graph->title->Set(utf8_decode($title));
            $graph->subtitle->Set(utf8_decode($subtitle));
            $graph->yaxis->SetTitle($yaxistitle,'middle'); 
            $graph->xaxis->SetTickLabels($label);
            $graph->xaxis->SetTextLabelInterval($step);
            $graph->xaxis->SetLabelAngle(90);

 
 
     
            $barplot= $this->_barPlot($value[$key],'red');
            $barplot->value->Show();
            $barplot->value->SetFont(FF_ARIAL,FS_BOLD,8);
            $barplot->value->SetAngle(90);
            
            
            $barplot->value->SetFormat($format);
            
            
            $barplot->SetValuePos('center');
            $barplot->SetFillGradient($color.'@0.3',$color.'@0.6',GRAD_VERT);
            $barplot->SetWidth(1);
            $barplot->SetValuePos('center');
            $graph->Add($barplot);

           
            $txt = new Text($text1);
            $txt->SetPos($width-145, 30);
            $txt->SetFont(FF_ARIAL,FS_ITALIC,9);
            
            $txt2 = new Text($text2);
            $txt2->SetPos($width-90, 30);
            $txt2->SetFont(FF_ARIAL,FS_NORMAL,9);
            
      
            $graph->AddText($txt); 
            $graph->AddText($txt2); 
          
      
            $graph->footer->left->Set(utf8_decode("Fuente: Suma de consumos de clientes en sala"));
            $graph->Stroke();
        }

    }
  */

    
    
}










